#include "hk32c030xx.h"
#include "hk32c030xx_misc.h"
#include "system_hk32c030xx.h"
#include "FreeRTOSConfig.h"
#include "systick.h"
#include <stdint.h>
#include "FreeRTOSConfig.h"

static uint32_t _g_us_ticks = 0;

void systick_config(void) {

	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
	
    _g_us_ticks = SystemCoreClock / 8000000;
    uint32_t reload_ticks = _g_us_ticks * 1000000 / SYSTICK_INT_FREQ;
    
    SysTick->LOAD = reload_ticks;
	SysTick->VAL = 0;
	
    /* configure the systick handler priority */
	NVIC_SetPriority(SysTick_IRQn, 0x00U);
    SysTick->CTRL = SysTick_CTRL_ENABLE_Msk | SysTick_CTRL_TICKINT_Msk;
}

void delay_ms(uint32_t count) {
    delay_us(count * 1000);
}

void delay_us(uint32_t count) {
    
    uint32_t _total_ticks = _g_us_ticks * count;
    uint32_t _reload = SysTick->LOAD;
    uint32_t _t_old = SysTick->VAL;
    uint32_t _t_count = 0;

    while(_t_count <= _total_ticks) {
        uint32_t _t_now = SysTick->VAL;
        if(_t_now != _t_old) {
            if(_t_now < _t_old) {
                _t_count += _t_old - _t_now;
            } else {
                _t_count += _reload + _t_old - _t_now;
            }
            _t_old = _t_now;
        }
    }
}
